// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init();

/**
 * 获得文章的所有评论
 * event参数说明：
 * @param {*} skip 跳过的记录数（TODO）
 * @param {*} limit 数量限制
 * 返回值说明：
 * errCode：错误码，0-正常
 * data：数据部分，数组包括每条评论，根据masterId分组，comment的评论本身，对评论的回复（楼中楼）在replyList中
 * 数组元素样例：
 * {
    "_id": "8f75309d62a443cb080ea95e34633325",
    "replyList": [{
      "_id": "0ab5303b62a4459a08d051102d6b5ff7",
      "_openid": "o9Ifc5BXNXoDvCX1dub-LLSK928I",
      "postId": "f6e08a6462a2c1800766a7b46c7be2bd",
      "masterId": "8f75309d62a443cb080ea95e34633325",
      "nickName": "lyc",
      "replyTo": "o9Ifc5BXNXoDvCX1dub-LLSK928I",
      "time": "2022-6-11-15-34-48",
      "avatarUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/N9IHq7Qkjq6oorguhJG8YcMgZGibu4Sz8ujS1Ns6SaNYMicySHw4icOvvic58xAXrxNE2leNsiahS6lMcRU4iamwfXlw/132",
      "content": "好个p，爬"
    }],
    "comment": {
      "_id": "8f75309d62a443cb080ea95e34633325",
      "_openid": "o9Ifc5BXNXoDvCX1dub-LLSK928I",
      "postId": "f6e08a6462a2c1800766a7b46c7be2bd",
      "masterId": "8f75309d62a443cb080ea95e34633325",
      "nickName": "lyc",
      "replyTo": null,
      "time": "2022-6-11-15-27-6",
      "avatarUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/N9IHq7Qkjq6oorguhJG8YcMgZGibu4Sz8ujS1Ns6SaNYMicySHw4icOvvic58xAXrxNE2leNsiahS6lMcRU4iamwfXlw/132",
      "content": "好，字词"
    }
  }
 */
exports.main = async (event, context) => {
  const db = cloud.database();
  const _ = db.command;
  const $ = _.aggregate;
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  const articleId = event.postId;

  var commentList = await db.collection('comment').aggregate()
    .match({
      postId: articleId
    })
    .lookup({
      from: 'user',
      let: {
        authorOpenid: '$_openid'
      },
      pipeline: $.pipeline()
        .match(_.expr($.eq(['$_openid', '$$authorOpenid'])))
        .project({
          nickName: 1,
          avatarUrl: 1
        })
        .done(),
      as: 'author'
    })
    .replaceRoot({newRoot: $.mergeObjects([$.arrayElemAt(['$author', 0]), '$$ROOT'])})
    .project({
      author: 0
    })
    .group({
      _id: '$masterId',
      replyList: $.push({
        _id: '$_id',
        _openid: '$_openid',
        postId: '$postId',
        masterId: '$masterId',
        nickName: '$nickName',
        replyTo: '$replyTo',
        time: '$time',
        avatarUrl: '$avatarUrl',
        content: '$content'
      })
    })
    .end();
  // 在分组后的评论的每组中，找到_id与分组_id相同的评论放到replyList之外
  for(var i in commentList.list){
    var replyList = commentList.list[i].replyList;
    for(var j in replyList){
      if(replyList[j]._id == commentList.list[i]._id){
        commentList.list[i].comment = replyList[j];
        replyList.splice(j ,1);
        break;
      }
    }
  }
  return {
    errCode: 0,
    data: commentList.list
  };
}